import {showModal, showToast} from "../../utils/asyncWx"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    cart: [],
    allChecked:false,
    totalPrice: 0,
    totalNum: 0
  },

  onShow() {
    let address = wx.getStorageSync("address");
    //获取缓存中购物车数据
    let cart = wx.getStorageSync("cart") || [];
    //空数组调用every() 返回true
    // let allChecked =cart.length ? cart.every(v => v.checked) : false
    this.setData({address})
    this.setCart(cart)

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  //收货地址
  handleChooseAddress() {
    //获取
    wx.chooseAddress({
      success: (result)=>{
        console.log(result);
        wx.setStorageSync("address", result);
      }
    });
  },

  // 商品的选中
  handleItemChange(e) {
    console.log(e);
    //获取被修改的商品的id
    let goods_id = e.currentTarget.dataset.id
    // console.log(goods_id);
    //获取购物车数组
    let {cart} = this.data
    //找到被修改的商品对象
    let index = cart.findIndex(v =>v.goods_id === goods_id)
    //选中状态取反
    cart[index].checked = !cart[index].checked
    //把购物车数据重新设置会data中和缓存中
    this.setCart(cart)
  },

  //设置购物车状态的同时 重新计算 底部工具栏的数据 全选 总价格 购买的数量
  setCart(cart) {      
    let allChecked = true
    //总数量 总价格
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price
        totalNum += v.num
      } else {
        allChecked = false
      }
      
    })
    allChecked = cart.length != 0 ? allChecked : false
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNum
    })
    wx.setStorageSync("cart", cart)
  },

  handleItemAllChange() {
    let {cart, allChecked} = this.data
    allChecked = !allChecked
    cart.forEach(v => {
      v.checked = allChecked
    })
    this.setCart(cart)
  },

  //商品数量的操作
  async handleItemNumEdit(e) {
    let {id, operation} = e.currentTarget.dataset
    // console.log(id, operation);
    let {cart} = this.data
    let index = cart.findIndex(v => v.goods_id === id)
    if (cart[index].num === 1 && operation === -1) {
    
      let result = await showModal({content: "是否删除该商品"})
      if(result.confirm){
        cart.splice(index, 1)
        this.setCart(cart)

      } 
    } else {
        cart[index].num += operation
        this.setCart(cart)
    }
   
  },

  //点击 结算
  async handlePay() {
    //判断收货地址
    let {address, totalNum} = this.data
    if (!address.userName) {
      await showToast({title:"没有地址俄(ToT)/~~~"})
      return
    }

    if (totalNum === 0) {
      await showToast({title:"选一件吧~"})
      return
    }
    wx.navigateTo({
      url: '/pages/pay/index',
    });
  }
})